package com.cjhedu.web.advice;

import com.cjhedu.web.domain.OperateLog;
import com.cjhedu.web.mapper.OperateLogMapper;
import com.cjhedu.web.utils.MyThreadLocalUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author 陈佳豪
 * @version 1.0
 */
@Component
@Aspect
public class MyLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("execution(* com.cjhedu.web.service.*.*(..))")
    public Object totalTime(ProceedingJoinPoint pjp) throws Throwable {
        String name = pjp.getSignature().getName();
        if ("login".equals(name)){
            Object proceed = pjp.proceed();
            return proceed;
        }
        //增强逻辑
        long start = System.currentTimeMillis();
        Object o = null;
        try {
            o = pjp.proceed();
        } finally {
            long end = System.currentTimeMillis();
            Map<String, Object> map = MyThreadLocalUtils.getValue();
            Integer userId = Integer.parseInt(map.get("id").toString());
            //准备数据
            OperateLog build = OperateLog.builder()
                    .operateUser(userId)
                    .operateTime(LocalDateTime.now())
                    .className(pjp.getSignature().getDeclaringTypeName())
                    .methodName(name)
                    .methodParams(pjp.getArgs().toString())
                    .returnValue(o==null ? "null" : o.toString())
                    .costTime(end - start)
                    .build();
            operateLogMapper.insert(build);
        }
        return o;
    }
}